package org.exhaust.framework.net.common.protocol.decoder.udp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.exhaust.framework.net.common.protocol.BaseFrame;
import org.exhaust.framework.net.common.protocol.decoder.ByteBufDecoderHelper;
import org.exhaust.framework.net.common.protocol.handler.BusinessDataHandler;
import org.exhaust.framework.net.common.protocol.BaseUdpFrame;

@Slf4j
public class UdpDecoder extends SimpleChannelInboundHandler<DatagramPacket> {

    private ByteBufDecoderHelper<BaseFrame> decoderHelper;

    private BusinessDataHandler<BaseUdpFrame> handler;

    public UdpDecoder(ByteBufDecoderHelper<BaseFrame> decoderHelper, BusinessDataHandler<BaseUdpFrame> handler) {
        this.decoderHelper = decoderHelper;
        this.handler = handler;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        final ByteBuf content = msg.content();
        String hexDump = ByteBufUtil.hexDump(content);
        log.info("decode udp msg:{}", hexDump);
        final BaseFrame decode = decoderHelper.decode(ctx, content);
        if (decode != null) {
            BaseUdpFrame udpFrame = new BaseUdpFrame(decode);
            udpFrame.setSender(msg.sender());
            udpFrame.setRecipient(msg.recipient());
            handler.receiveMsg(ctx, udpFrame);
        }
    }
}
